package com.elitel.frame.aspect;

import com.elitel.frame.main.common.datasource.DBContextHolder;
import com.elitel.frame.main.entity.CfgDb;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class DataBaseAspect {

    @Pointcut("execution(* com.elitel.frame.business.service.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void checkSecurity(JoinPoint joinPoint) {
        Object[] ob = joinPoint.getArgs();
        int index = 0;
        for(int i=0;i<ob.length;i++) {
            if(null != ob[i] && "com.elitel.frame.main.entity.CfgDb".equals(ob[i].getClass().getName())) {
                index = i;
                break;
            }
        }
        if (!"com.elitel.frame.main.entity.CfgDb".equals(ob[index].getClass().getName())) {
           return;
        }
        CfgDb cfgDb = (CfgDb)ob[index];
        if(cfgDb==null) {
            //选择默认数据源
            DBContextHolder.clearDBType();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(DBContextHolder.DATASOURCE_KEY, cfgDb.getDbKey());
        map.put(DBContextHolder.DATASOURCE_DRIVER, cfgDb.getDbDrivername());
        map.put(DBContextHolder.DATASOURCE_URL,cfgDb.getDbUrl());
        map.put(DBContextHolder.DATASOURCE_USERNAME,cfgDb.getDbUser());
        map.put(DBContextHolder.DATASOURCE_PASSWORD, cfgDb.getDbPwd());
        DBContextHolder.setDBType(map);
    }
}
